package com.hongyi.modelcontest.core.util;

import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Component
public class SpringbootUtils {
    /**
     * Spring应用上下文环境
     */
    @Resource
    private ApplicationContext applicationContext;
    private static ApplicationContext context;

    @PostConstruct
    public void init() {
        context = applicationContext;
    }


    public static String getRealPath() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String path = request.getSession().getServletContext().getRealPath("");
        return new File(path).getParent();
    }

    public static String getRemotUrl() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        request.getRemoteAddr();
        return "http://" + request.getServerName();
    }

    // 传入线程中
    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    /// 获取当前环境
    public static String getActiveProfile() {
        Environment environment = context.getEnvironment();
        return environment.getActiveProfiles()[0];
    }
}
